package com.hzjh.h5mall.ui.ads

import android.annotation.SuppressLint
import android.view.KeyEvent
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.hzjh.base.ext.frame.JHBaseActivity
import com.hzjh.base.ext.route.RouteUrl
import com.hzjh.base.ext.utils.NumberUtils
import com.hzjh.base.frame.adapter.MutableAdapter
import com.hzjh.base.frame.adapter.SimpleGapItemDecor
import com.hzjh.base.style.view.dialog.ConfirmDialog
import com.hzjh.base.style.weight.GlideUtils.loadCenterCorp
import com.hzjh.base.utils.function.dp2px
import com.hzjh.base.utils.function.visibleOrGone
import com.hzjh.base.utils.other.CheckUtils
import com.hzjh.base.utils.other.CommUtils
import com.hzjh.h5mall.R
import com.hzjh.h5mall.adapter.ads.JHOrderPlatformItemVH
import com.hzjh.h5mall.bean.AdOrderStatus
import com.hzjh.h5mall.databinding.ActivityAdsOrderDetailBinding
import com.hzjh.h5mall.databinding.ItemOrderPlatfromBinding
import com.hzjh.h5mall.model.ads.AdsModel
import com.hzjh.h5mall.myinterface.AdsOrderI

@Route(path = RouteUrl.ADS_ORDER_ACTIVITY_DETAIL)
class AdsOrderDetailActivity : JHBaseActivity<ActivityAdsOrderDetailBinding, AdsModel>(),AdsOrderI {
    @JvmField
    @Autowired(name = RouteUrl.PARAMS_TASK_ID)
    var mTaskId: String = "" //任务id

    private val fragments = ArrayList<AdsOrderDetailFragment>()
    private var currentPosition = 0

    private val platformAdapter by lazy {
        MutableAdapter(viewModel.platformList.value!!).apply {
            addVhDelegate {
                JHOrderPlatformItemVH(ItemOrderPlatfromBinding.inflate(layoutInflater, it, false),
                    changePlatform = { item, position ->
                        //选择平台
                        switchPage(position, currentPosition)
                    },
                    changeSelectItem = { binding, position ->
                        //选择平台
                        binding.rlPlatformItem.setBackgroundResource(if(position==currentPosition
                            &&viewModel.adsDetailBean.value?.state!=AdOrderStatus.REJECT.value
                                    &&viewModel.adsDetailBean.value?.state!=AdOrderStatus.CANCEL.value
                                    &&viewModel.adsDetailBean.value?.state!=AdOrderStatus.TIMEOUT.value) com.hzjh.base.ext.R.drawable.bg_rect_stroke_red_grey else com.hzjh.base.style.R.color.coreBackGround2)
                    }
                )
            }
        }
    }

    override fun initData() {
        viewModel.reqAdsOrderDetail(mTaskId)
    }

    override fun initView() {
        viewBinding.barTitle.clickBackBtn{
            clickBack()
        }
        viewBinding.rvPlatform.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        viewBinding.rvPlatform.addItemDecoration(
            SimpleGapItemDecor(horGap = 24.dp2px())
        )
        viewBinding.rvPlatform.adapter=platformAdapter

        viewBinding.btnSub.setOnClickListener {
            //获取填写的平台数据
            fragments[currentPosition].submitPlatformData()
        }
    }

    override fun initObservable() {
        super.initObservable()
        viewModel.adsDetailBean.observe(this){
            viewBinding.ivOrderDetail.loadCenterCorp(it.avatar)
            viewBinding.tvPrice.text = it.price
            viewBinding.tvViewsTag.text = NumberUtils.formatNumber(it.views)
            viewBinding.tvTime.text = NumberUtils.formatTime(it.sysTime,it.overTime)
            changeAdStatus()
            it.advertisingInfoList.mapIndexed {_,adsTaskDetailBean ->
                adsTaskDetailBean.adsMainStatus=it.state
                it.platforms.forEach {adsPlatformBean ->
                    if(adsTaskDetailBean.type==adsPlatformBean.value){
                        adsTaskDetailBean.platformIcon=adsPlatformBean.remarks
                    }
                }
            }
            viewModel.setPlatformData(it.advertisingInfoList)
            changeBtnStatus()
        }
        viewModel.platformList.observe(this){
            //平台相关信息
            platformAdapter.notifyDataSetChanged()
            if(fragments.size==0){
                viewModel.platformList.value?.forEach { item ->
                    val orderDetailFragment =
                        ARouter.getInstance().build(RouteUrl.ADS_ORDER_FRAGMENT_DETAIL).navigation() as AdsOrderDetailFragment
                    orderDetailFragment.setData(item)
                    fragments.add(orderDetailFragment)
                }
                if(fragments.size>0){
                    supportFragmentManager
                        .beginTransaction()
                        .replace(R.id.fl_container, fragments[0])
                        .commitNow()
                }
            }
        }
    }

    private fun changeAdStatus() {
        viewModel.adsDetailBean.value?.let {
            //状态，state 状态，0进行中，10待审核，20已审核，25待打款，30财务打款完成，99拒绝,98超时,97取消
            when(it.state){
                AdOrderStatus.ACCEPT.value,
                AdOrderStatus.WAITING.value,
                AdOrderStatus.REVIEWED.value,
                AdOrderStatus.PENDING_PAY.value->{
                    viewBinding.tvAdStatus.text=CommUtils.getString(com.hzjh.base.ext.R.string.jh_state_accepted)
                    viewBinding.rlRevenue.visibleOrGone(false)
                    if(it.state==AdOrderStatus.PENDING_PAY.value) {
                        viewBinding.rlRevenue.visibleOrGone(!CheckUtils.isEmpty(it.money)) {
                            //显示金额
                            viewBinding.tvOrderMoney.text = "$${it.money}"
                        }
                    }
                }
                AdOrderStatus.COMPLETE.value->{
                    viewBinding.tvAdStatus.text=CommUtils.getString(com.hzjh.base.ext.R.string.jh_state_completed)
                    viewBinding.rlRevenue.visibleOrGone(!CheckUtils.isEmpty(it.money)){
                        //显示金额
                        viewBinding.tvOrderMoney.text = "$${it.money}"
                    }
                    viewBinding.btnSub.visibleOrGone(false)
                }
                AdOrderStatus.CANCEL.value,
                AdOrderStatus.TIMEOUT.value,
                AdOrderStatus.REJECT.value->{
                    viewBinding.tvAdStatus.text=CommUtils.getString(com.hzjh.base.ext.R.string.jh_state_canceled)
                    viewBinding.btnSub.visibleOrGone(false)
                    viewBinding.tvPlatformTitle.visibleOrGone(false)
                    viewBinding.tvAdExpiredInfo.visibleOrGone(true){
                        var ifHaveReview = false //是否上传过平台
                        it.advertisingInfoList.forEach {adsTaskDetailBean->
                            if(!CheckUtils.isEmpty(adsTaskDetailBean.url)){
                                ifHaveReview = true
                            }
                        }
                        viewBinding.llOrderContent.visibleOrGone(ifHaveReview)
                        text = if(it.state==AdOrderStatus.CANCEL.value){
                            //取消
                            CommUtils.getString(com.hzjh.base.ext.R.string.jh_order_canceled)
                        }else if(it.state==AdOrderStatus.REJECT.value){
                            //拒绝
                            CommUtils.getString(com.hzjh.base.ext.R.string.jh_order_terminated)
                        }else if(ifHaveReview){
                            //过期 已上传平台
                            CommUtils.getString(com.hzjh.base.ext.R.string.jh_order_expired)
                        }else {
                            //过期 未上传平台
                            CommUtils.getString(com.hzjh.base.ext.R.string.jh_order_not_uploaded)
                        }

                    }
                }
            }
        }
    }

    @SuppressLint("CommitTransaction")
    private fun switchPage(index: Int,oldIndex:Int) {
        if(index==oldIndex||index>=fragments.size){
            return
        }
        val nowFragment = fragments[index]
        supportFragmentManager.beginTransaction().apply {
            if (!nowFragment.isAdded) {
                add(R.id.fl_container, nowFragment)
            }
            show(nowFragment)
            hide(fragments[oldIndex])
            commit()
        }
        currentPosition = index
        platformAdapter.notifyDataSetChanged()
        changeBtnStatus()
    }
    override fun changeBtnStatus() {
        CommUtils.getHandler().postDelayed({
            val nowFragment = fragments[currentPosition]
            viewBinding.btnSub.isEnabled = nowFragment.checkNotEmpty()
        }, 200)
        var platfrom=""
        if((viewModel.platformList.value?.size ?: 0) > currentPosition){
            platfrom=viewModel.platformList.value?.get(currentPosition)?.type?:""
        }
        viewBinding.btnSub.text = CommUtils.getString(com.hzjh.base.ext.R.string.jh_ad_submit,platfrom)
    }

    override fun initViewBinding(): ActivityAdsOrderDetailBinding {
        return ActivityAdsOrderDetailBinding.inflate(layoutInflater)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            clickBack()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun clickBack(){
        if(viewModel.adsDetailBean.value?.state==0
            ||viewModel.adsDetailBean.value?.state==10
            ||viewModel.adsDetailBean.value?.state==20){
            //审核中或者待审核
            ConfirmDialog.Builder(this)
                .setMessage(CommUtils.getString(com.hzjh.base.ext.R.string.jh_exit_task_detail))
                .setCancelButton(CommUtils.getString(com.hzjh.base.ext.R.string.jh_directly_leave)){ dialog, _ ->
                    finish()
                }.setSureButton(CommUtils.getString(com.hzjh.base.ext.R.string.jh_cancel)) { dialog, _ ->
                    dialog.dismiss()
                }.setCanCancel(true).create().show()
        }else{
            finish()
        }
    }

    override fun switchNextPage() {
        switchPage((currentPosition + 1)%3, currentPosition)
        platformAdapter.notifyDataSetChanged()
    }
}